package com.fable.common.configura.shiro;

import com.alibaba.druid.util.StringUtils;
import com.fable.sgms.user.dao.entity.SysUser;
import com.fable.sgms.user.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AuthorizingRealm extends org.apache.shiro.realm.AuthorizingRealm {


    @Autowired
    private UserService userService;

    private Logger _log = LoggerFactory.getLogger(getClass());

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        _log.debug("用户认证开始:用户名：{}", token.getPrincipal());
        UsernamePasswordToken t = (UsernamePasswordToken) token;

        String userName = t.getUsername();
        String password = new String((char[]) t.getCredentials());

        SysUser entity = userService.findByUserName(userName);

        //账号不存在
        if (entity == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //密码错误
        if (!password.equals(entity.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        //密码错误
        if (entity.getStatus() != 1) {
            throw new IncorrectCredentialsException("账号被禁用");
        }

        _log.debug("登录用户信息:{}", entity.toString());

        if (StringUtils.isEmpty(entity.getId())) {
            return null;
        }

        return new SimpleAuthenticationInfo(entity.getUserName(), entity.getPassword(), this.getName());
    }
}
